package com.cdyx.outsideprescription.service.impl;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cdyx.outsideprescription.BO.EpcInfoBo;
import com.cdyx.outsideprescription.config.EcpConfig;
import com.cdyx.outsideprescription.config.PrescriptionUploadConfig;
import com.cdyx.outsideprescription.dto.EpcInfoDto;
import com.cdyx.outsideprescription.dto.EpcListDto;
import com.cdyx.outsideprescription.dto.queryEpcDto;
import com.cdyx.outsideprescription.entity.TbEpcinfo;
import com.cdyx.outsideprescription.mapper.TbEpcinfoMapper;
import com.cdyx.outsideprescription.mapper.TbEpclistMapper;
import com.cdyx.outsideprescription.service.ITbEpcinfoService;
import com.cdyx.outsideprescription.util.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jiang dongqiong
 * @since 2021-12-27
 */
@Slf4j
@Service("tbEpcinfoServiceImpl")
@Transactional
public class TbEpcinfoServiceImpl extends ServiceImpl<TbEpcinfoMapper, TbEpcinfo> implements ITbEpcinfoService {
    @Autowired
    TbEpcinfoMapper epcinfoMapper;
    @Autowired
    TbEpclistMapper epclistMapper;
    @Autowired
    PrescriptionUploadConfig prescriptionUploadConfig;
    @Autowired
    RestTemplate restTemplate;
    @Autowired
    EcpConfig config;
    @Transactional(rollbackFor = Exception.class)
    @Override
    public long createEpc(Map<String, Object> data) {
        long l = SnowFlakeUtil.nextId();
        int i=0;
        data.put("own_epc_id",l);
        if (data.get("org_med_type").toString().equals("11")){
            List<Map<String, String>> mothYear = CalendarUtil.getYearMoth();
             i=epcinfoMapper.insertEpcInfo(data,mothYear);

        }else{
            i=epcinfoMapper.insertEpcInfozy(data);
        }
        if (i==0){
            return i;
        }else{
            Object epcObj = data.get("epclist");
            List<Map<String,String>> epcList=new ArrayList<>();
            if (epcObj instanceof ArrayList<?>){
                for (Object o:(List<?>)epcObj
                ) {
                    epcList.add(Map.class.cast(o));
                }
            }
            epclistMapper.insertEpcList(epcList,l);
            return l;
        }

    }
    @Transactional(rollbackFor = Exception.class)
    @Async
    @Override
    public void pushEpcInfo(Map<String, Object> data, long ID) throws ParseException {
        Calendar calendar=Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        Map<String,Object> epcInfo=new HashMap<>();
        List<Map<String,Object>> epcList=new ArrayList<>();
        epcInfo.put("dscg_main_dise_codg",data.get("dscg_main_dise_codg"));
        epcInfo.put("dscg_main_dise_name",data.get("dscg_main_dise_name"));
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.DAY_OF_MONTH, Integer.parseInt(data.get("end_time").toString()));
        Date time = instance.getTime();
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String endTime = simpleDateFormat.format(time);
        epcInfo.put("end_time",endTime);
        epcInfo.put("epc_sort",data.get("epc_sort"));
        epcInfo.put("epc_type",data.get("epc_type"));
        epcInfo.put("visitNo",data.get("visitNo"));
        epcInfo.put("org_med_type",data.get("org_med_type"));
        epcInfo.put("year",year);
        Object epcObj = data.get("epclist");
        if (epcObj instanceof ArrayList<?>){
            for (Object o:(List<?>)epcObj
            ) {
                epcList.add(Map.class.cast(o));
            }
        }
        HashMap<String,Object> epc=new HashMap<>();
        EpcInfoDto epcInfoDto=null;
        if (data.get("org_med_type").toString().equals("11")){
            List<Map<String, String>> mothYear = CalendarUtil.getYearMoth();
            epcInfoDto=epcinfoMapper.selectEpcInfo(epcInfo,mothYear);
        }else{
            epcInfoDto=epcinfoMapper.selectEpcInfozy(epcInfo);
        }
        List<EpcListDto> epcListDto=epclistMapper.selectEpcList(epcList);
        epcInfoDto.setEpclist(epcListDto);
        String createEpcYUrl = prescriptionUploadConfig.getCreateEpc();
        log.info("上传地址==============>"+createEpcYUrl);
       // net.sf.json.JSONObject jsonObject = net.sf.json.JSONObject.fromObject(epcInfoDto);
      //  String epcinfo = JSON.toJSONString(jsonObject);
       // Object epcl = com.alibaba.fastjson.JSONArray.toJSON(epcListDto);
       // String epcinfoList=JSON.toJSONString(epcl);
        epc.put("data",epcInfoDto);
        String code = data.getOrDefault("operCode","061").toString();
        String name = data.getOrDefault("operName", "操作员").toString();
        EpcInfoBo epcInfoBo = getUploadData(epc,code,name,"9211");
        String s = JSON.toJSONString(epcInfoBo);
        log.info("=======================>"+s);
        HttpEntity formEntity = HttpUtils.getEntity(s);
        log.info("============================>");
        log.info("上传处方--->epcInfoMap"+s);
        HashMap resMap = restTemplate.postForObject(createEpcYUrl, formEntity, HashMap.class);
        log.info("==================================");
        log.info("上传文件返回值====>resMap"+resMap);
        log.info("==================================");
        String resMapObject = JSON.toJSONString(resMap);
        log.info("返回的json"+resMapObject);
        int status=-1;
        if (resMap.containsKey("infcode")){
            status=Integer.parseInt(resMap.get("infcode").toString());
        }else if (resMap.containsKey("code")){
            status=Integer.parseInt(resMap.get("code").toString());
        }
        if (status==0){
            Map<String,Object> output =(Map<String,Object>) resMap.get("output");
            Map<String,String> outData = (Map<String,String>)output.get("data");
            String psn_no=outData.get("psn_no");
            String epc_id = outData.get("epc_id");
            String expContent = outData.get("expContent");
            log.info("修改状态开始");
            epcinfoMapper.updateInfo(psn_no,epc_id,expContent,ID);
            log.info("修改状态完成");
            epclistMapper.updateInfo(epc_id,expContent,ID);
        }


    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, String> pushEpcInfoReal(Map<String, Object> data) {
        Calendar calendar=Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        Map<String,Object> epcInfo=new HashMap<>();
        List<Map<String,Object>> epcList=new ArrayList<>();
       // SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //String end_time = simpleDateFormat.format(data.get("end_time").toString());
        epcInfo.put("dscg_main_dise_codg",data.get("dscg_main_dise_codg"));
        epcInfo.put("dscg_main_dise_name",data.get("dscg_main_dise_name"));
        epcInfo.put("end_time",data.get("end_time"));
        epcInfo.put("epc_sort",data.get("epc_sort"));
        epcInfo.put("epc_type",data.get("epc_type"));
        epcInfo.put("visitNo",data.get("visitNo"));
        epcInfo.put("org_med_type",data.get("org_med_type"));
        epcInfo.put("year",year);
        Object epcObj = data.get("epclist");
        if (epcObj instanceof ArrayList<?>){
            for (Object o:(List<?>)epcObj
            ) {
                epcList.add(Map.class.cast(o));
            }
        }
        HashMap<String,Object> epc=new HashMap<>();
        log.info("开始info组织数据----------》");
        EpcInfoDto epcInfoDto=null;
        if (data.get("org_med_type").toString().equals("11")){
            List<Map<String, String>> mothYear = CalendarUtil.getYearMoth();
             epcInfoDto=epcinfoMapper.selectEpcInfo(epcInfo,mothYear);

        }else{
            epcInfoDto=epcinfoMapper.selectEpcInfozy(epcInfo);
        }
        log.info("完成info组织数据----------》");
        log.info("开始epcList组织数据----------》");
        List<EpcListDto> epcListDto=epclistMapper.selectEpcList(epcList);
        epcInfoDto.setEpclist(epcListDto);
        log.info("完成epcList组织数据----------》");
        String createEpcYUrl = prescriptionUploadConfig.getCreateEpc();
        log.info("上传地址==============>"+createEpcYUrl);
        epc.put("data",epcInfoDto);
        String code = data.getOrDefault("operCode","061").toString();
        String name = data.getOrDefault("operName", "操作员").toString();
        EpcInfoBo epcInfoBo = getUploadData(epc,code,name,"9211");
        String s = JSON.toJSONString(epcInfoBo);
        log.info("上传文件值------->"+s);
        log.info("=======================>");
        HttpEntity formEntity = HttpUtils.getEntity(s);
        HashMap resMap = restTemplate.postForObject(createEpcYUrl, formEntity, HashMap.class);
        log.info("======================");
        log.info("上传文件返回值"+resMap.toString());
        HashMap<String,String> map=new HashMap<>();
        int status=-1;
        if (resMap.containsKey("infcode")){
            status=Integer.parseInt(resMap.get("infcode").toString());
        }else if (resMap.containsKey("code")){
            status=Integer.parseInt(resMap.get("code").toString());
        }
        if (status==0){
            Map<String,Object> output =(Map<String,Object>) resMap.get("output");
            Map<String,String> outData = (Map<String,String>)output.get("data");
            String psn_no=outData.get("psn_no");
            String epc_id = outData.get("epc_id");
            String expContent = outData.get("expContent");
            long id = Long.parseLong(data.get("id").toString());
            log.info("开始改变上传状态");
            epcinfoMapper.updateInfo(psn_no,epc_id,expContent,id);
            log.info("改变状态完成");
            epclistMapper.updateInfo(epc_id,expContent,id);
            map.put("psn_no",psn_no);
            map.put("epc_id",epc_id);
            map.put("status","1");
            map.put("expContent",expContent);
            return map;
        }else{
            map.put("status","-1");
            map.put("message",resMap.get("message").toString());
            return map;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<Map<String, Object>> queryEpcInfo(Map<String, Object> data) {
        List<Map<String,Object>> queryEpc=new ArrayList<>();
        Map<String,Object> epc=new HashMap<>();
        Map<String,Object> entity=new HashMap<>();
        entity.put("data",data);
        String epc_id = data.get("epc_id").toString();
        String code = data.getOrDefault("operCode","061").toString();
        String name = data.getOrDefault("operName", "操作员").toString();
        EpcInfoBo uploadData = getUploadData(entity,code,name,"9212");
        HashMap epcInfoMap = JSON.parseObject(JSON.toJSONString(uploadData), HashMap.class);
        String s = JSON.toJSONString(epcInfoMap);
        String queryEpcInfoURL = prescriptionUploadConfig.getQueryEpcInfo();
        log.info("=================查询数据======>"+s);
        HttpEntity formEntity = HttpUtils.getEntity(s);
        HashMap resMap = restTemplate.postForObject(queryEpcInfoURL, formEntity, HashMap.class);
        log.info("===========查询返回的信息==============resmap");
        log.info(JSON.toJSONString(resMap));
        if (Integer.parseInt(resMap.get("infcode").toString())==0){
            Map<String,Object> output =(Map<String,Object>) resMap.get("output");
            Map<String,Object> epcinfo = (Map<String,Object>)output.get("epcinfo");
            epcinfoMapper.updateInfobyReturn(epcinfo,epc_id);
            List<Map<String,Object>> epcList=new ArrayList<>();
            Object list = output.get("epclist");
            if (list instanceof ArrayList<?>){
                for (Object o:(List<?>)list
                ) {
                    epcList.add(Map.class.cast(o));
                }
            }
            long own_epc_id=epclistMapper.selectId(epc_id);
            epclistMapper.updateList(epcList,epc_id,own_epc_id);
            epcinfo.put("epcListDtoList",epcList);
           // epc.put("epcinfo",epcinfo);
          //  epc.put("epclist",epcList);
            queryEpc.add(epcinfo);
            return queryEpc;
        }
        return null;
    }
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int undoEpc(Map<String, Object> data) {
        Map<String,Object> entity=new HashMap<>();
        entity.put("data",data);
        String code = data.getOrDefault("operCode","061").toString();
        String name = data.getOrDefault("operName", "操作员").toString();
        EpcInfoBo uploadData = getUploadData(entity,code,name,"9213");
        String s = JSON.toJSONString(uploadData);
        log.info("============撤销处方===========>");
        log.info(s);
        HttpEntity formEntity = HttpUtils.getEntity(s);
        String queryEpcInfoURL = prescriptionUploadConfig.getUndoEpcInfo();
        HashMap resMap = restTemplate.postForObject(queryEpcInfoURL, formEntity, HashMap.class);
        log.info("=========================");
        log.info("撤销返回的res===>"+resMap);
        if (Integer.parseInt(resMap.get("infcode").toString())==0){
            int i=epcinfoMapper.updateStatus(data);
            return i;
        }else {
            return -1;
        }
    }

    @Override
    public List<queryEpcDto> queryEpc(Map<String,Object> data) {
        return epcinfoMapper.selectEpc(data);
    }

    public EpcInfoBo getUploadData(Map<String, Object> epc, String code, String name, String sign){
        EpcInfoBo epcInfoBo = config.init();
        String fixmedins_code = epcInfoBo.getMsgid();
        epcInfoBo.setOpter(code);
        epcInfoBo.setOpter_name(name);
        epcInfoBo.setInfno(sign);
        SimpleDateFormat date=new SimpleDateFormat("yyyyMMddHHmmss");
        Date d=new Date();
        String nowDate = date.format(d);
        Random random=new Random();
        int x=random.nextInt(9999-1000+1)+1000;
        String msgId=fixmedins_code+nowDate+x;
        epcInfoBo.setMsgid(msgId);
        SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        dateFormat.format(d);
        epcInfoBo.setInf_time(nowDate);
        //String s = JSON.toJSONString(epc);
        epcInfoBo.setInput(epc);
        return epcInfoBo;
    }
}
